#pragma once

#include <iostream>
#include <cstring>
#include <unordered_map>
#include <string>
#include <fstream>

#include "Log.hpp"

static const std::string D_filename="dict.txt";
static const std::string D_path="./";
static const std::string gsep=": ";

using namespace LogMoudle;

class Dict
{
private:
    bool Splitline(std::string& line,std::string& key,std::string& value,const std::string gsep) // WARNING?
    {
        int pos=line.find(gsep);
        if(pos==std::string::npos)
        {
            LOG(LogLevel::WARNNING)<<"word parsed error";
            return false;
        }
        key=line.substr(0,pos);
        value=line.substr(pos+gsep.size());
        if(key.empty() || value.empty()) return false;
        return true;
    }
    bool LoadDict()
    {
        const std::string file=_path+_filename;
        std::ifstream in(file.c_str());
        if(!in.is_open())
        {
            LOG(LogLevel::FATAL)<<file<<"open error";
            return false;
        }
        std::string line;
        while(std::getline(in,line))
        {
            std::string key,value;   //nullptr ??? 
            if(Splitline(line,key,value,gsep))
            {
                // _dictionary[key]=value;         
                _dictionary.insert(std::make_pair(key,value));
                //上面这两个有区别的，当key不存在时，都是添加到_dictionary 
                // 当key存在的时候，第一种写法则会重新赋值，而第二种写法则会直接忽略，以第一次写入为主。所以这里我们采用的是第二种写法
            }
            else return false;
        }
        in.close();
        return true;
    }

public:
    Dict(std::string path=D_path,std::string filename=D_filename)
    :_path(path),_filename(filename)
    {
       if(!LoadDict())
       {
         LOG(LogLevel::FATAL)<<"LoadDict error";
       }
        Print();
    }
    // 对外开放的接口
    std::string Translate(const std::string& word)
    {
       auto it=_dictionary.find(word);
        if(it==_dictionary.end()) return "None";
        return it->second;
    }
     ~Dict(){}
     void Print()
     {
         for(auto [key,value] : _dictionary)
         {
             std::cout<<key<<": " <<value<<std::endl;
         }
     }
private:
    std::unordered_map<std::string,std::string> _dictionary;
    std::string _filename;
    std::string _path;
};